package mspbots.tsheets.business.core.tsheetuser;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.tsheets.business.core.AbstractToolsUtil;
import mspbots.tsheets.business.core.sysuser.SysUser;
import mspbots.tsheets.business.core.sysuser.SysUserMapping;
import mspbots.tsheets.business.core.sysuser.SysUserMappingRepository;
import mspbots.tsheets.business.core.sysuser.SysUserRepository;
import mspbots.tsheets.business.core.times.AttendanceTime;
import mspbots.tsheets.business.core.times.TimeSheet;
import mspbots.tsheets.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.*;
import java.util.List;
import java.util.Optional;

/**
 * @author AlexBob
 */
@Log4j2
@Service
@Component
@RequiredArgsConstructor
public class TSheetUserReceiver extends AbstractToolsUtil {

//    private final TSheetUserRepository tSheetUserRepository;
    private final SysUserMappingRepository sysUserMappingRepository;
    private final SysUserRepository sysUserRepository;


    @RabbitListener(queues = "tsheets.users.tl")
    public void syncTimesheet(ResultMsg resultMsg) {
        JsonNode entity = resultMsg.getEntity();
        TSheetUser data = TSheetUser.builder()
                .tenantCode(resultMsg.getTenantId())
                .syncTime(resultMsg.getSyncDate())
                .sheetUserId(resultMsg.getId())
                .firstName(super.getStringValue(entity.get("first_name")))
                .username(super.getStringValue(entity.get("username")))
                .email(super.getStringValue(entity.get("email")))
                .active(super.getBooleanValue(entity.get("active")))
                .lastName(super.getStringValue(entity.get("last_name")))
                .lastModified(super.getDateTimeValue(entity.get("last_modified")))
                .created(super.getDateTimeValue(entity.get("created")))
                .build();

            // materialized view tsheet_user
//        this.tSheetUserRepository.findBySheetUserIdAndTenantCode(resultMsg.getId(), resultMsg.getTenantId())
//                .map(result -> {
//                    data.setId(result.getId());
//                    return data;
//                })
//                .defaultIfEmpty(data)
//                .flatMap(this.tSheetUserRepository::save).block(Duration.ofSeconds(10));


        if (StringUtils.isEmpty(data.getEmail())) {
            return;
        }

        SysUserMapping userMapping = this.sysUserMappingRepository
                .findByMappingUserIdAndUserTypeAndTenantCode(data.getSheetUserId().toString(),
                        SysUserMapping.USER_TYPE_TSHEET, data.getTenantCode()).block(Duration.ofSeconds(10));
        if (ObjectUtils.isEmpty(userMapping)){
            SysUser sysUser = this.sysUserRepository.findByEmailAndTenantCode(data.getEmail().toLowerCase(),
                    data.getTenantCode()).block(Duration.ofSeconds(10));
            if (ObjectUtils.isEmpty(sysUser)) {
                return;
            }
            SysUserMapping sysUserMapping = SysUserMapping.builder()
                    .userId(sysUser.getId())
                    .mappingUserId(data.getSheetUserId().toString())
                    .userType(SysUserMapping.USER_TYPE_TSHEET).build();
            sysUserMapping.setTenantCode(data.getTenantCode());
            sysUserMapping.setCreateDate(LocalDateTime.now());
            this.sysUserMappingRepository.save(sysUserMapping).block(Duration.ofSeconds(10));
        }

    }
}
